﻿namespace AppLab
{
    using System;
    using System.Net.NetworkInformation;
    using System.ServiceModel.DomainServices.Client;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Navigation;
    using AppLab.LoginUI;
    using AppLab.Web;
    using AppLab.Web.Services;
    using System.Windows.Browser;

    /// <summary>
    /// <see cref="UserControl"/> class providing the main UI for the application.
    /// </summary>
    public partial class MainPage : UserControl
    {
        /// <summary>
        /// Creates a new <see cref="MainPage"/> instance.
        /// </summary>
        public MainPage()
        {
            InitializeComponent();
            this.loginContainer.Child = new LoginStatus();
            WebContext.Current.Authentication.LoggedOut += new EventHandler<System.ServiceModel.DomainServices.Client.ApplicationServices.AuthenticationEventArgs>(Authentication_LoggedOut);
            NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
        }

        /// <summary>
        /// 用户注销返回首页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Authentication_LoggedOut(object sender, System.ServiceModel.DomainServices.Client.ApplicationServices.AuthenticationEventArgs e)
        {
            this.ContentFrame.Navigate(new Uri("/History", UriKind.Relative));
        }

        /// <summary>
        /// 网络断开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
        {
            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                //MessageBox.Show("网络连接有问题，请检查网络设备！", "网络", MessageBoxButton.OK);
                this.busyIndicatorNetWork.IsBusy = true;
            }
            else
            {
                this.busyIndicatorNetWork.IsBusy = false;
            }
        }

        /// <summary>
        /// After the Frame navigates, ensure the <see cref="HyperlinkButton"/> representing the current page is selected
        /// </summary>
        private void ContentFrame_Navigated(object sender, NavigationEventArgs e)
        {
            if (!WebContext.Current.User.IsAuthenticated)
            {
                this.ContentFrame.Navigate(new Uri("/History", UriKind.Relative));
            }

            foreach (UIElement child in LinksStackPanel.Children)
            {
                HyperlinkButton hb = child as HyperlinkButton;
                if (hb != null && hb.NavigateUri != null)
                {
                    if (hb.NavigateUri.ToString().Equals(e.Uri.ToString()))
                    {
                        VisualStateManager.GoToState(hb, "ActiveLink", true);
                    }
                    else
                    {
                        VisualStateManager.GoToState(hb, "InactiveLink", true);
                    }
                }
            }
        }

        /// <summary>
        /// If an error occurs during navigation, show an error window
        /// </summary>
        private void ContentFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            e.Handled = true;
            ErrorWindow.CreateNew(e.Exception);
        }

        #region 访问页面控制
        private FlowContext flow = new FlowContext();
        private int pageUriIndex = 0;

        private void TerminalInfoLinkButton_Click(object sender, RoutedEventArgs e)
        {
            this.PageJump(1);
        }

        private void SubmitLinkButton_Click(object sender, RoutedEventArgs e)
        {
            this.PageJump(2);
        }

        private void ReviewLinkButton_Click(object sender, RoutedEventArgs e)
        {
            this.PageJump(3);
        }

        private void TaskLinkButton_Click(object sender, RoutedEventArgs e)
        {
            this.PageJump(4);
        }

        private void PublishLinkButton_Click(object sender, RoutedEventArgs e)
        {
            this.PageJump(5);
        }

        private void RoleLinkButton_Click(object sender, RoutedEventArgs e)
        {
            this.PageJump(6);
        }

        private void PageJump(int pageIndex)
        {
            if (!WebContext.Current.User.IsAuthenticated)
            {
                MessageBox.Show("请先登录！", "页面访问", MessageBoxButton.OK);
                return;
            }
            this.IsEnabled = false;
            pageUriIndex = pageIndex;

            InvokeOperation<bool> invokeRole = flow.iUserInRole(pageUriIndex, WebContext.Current.User.Name);
            invokeRole.Completed += new EventHandler(invokeRole_Completed);
        }

        void invokeRole_Completed(object sender, EventArgs e)
        {
            InvokeOperation invokeOp = (InvokeOperation)sender;
            if (!(bool)invokeOp.Value)
            {
                MessageBox.Show("您没有权限访问该页！", "页面访问", MessageBoxButton.OK);
            }
            else
            {
                switch (pageUriIndex)
                {
                    case 1:
                        this.ContentFrame.Navigate(new Uri("/TerminalInfos", UriKind.RelativeOrAbsolute));
                        break;
                    case 2:
                        this.ContentFrame.Navigate(new Uri("/Submit", UriKind.RelativeOrAbsolute));
                        break;
                    case 3:
                        this.ContentFrame.Navigate(new Uri("/Review", UriKind.RelativeOrAbsolute));
                        break;
                    case 4:
                        this.ContentFrame.Navigate(new Uri("/Task", UriKind.RelativeOrAbsolute));
                        break;
                    case 5:
                        this.ContentFrame.Navigate(new Uri("/Publish", UriKind.RelativeOrAbsolute));
                        break;
                    case 6:
                        this.ContentFrame.Navigate(new Uri("/Role", UriKind.RelativeOrAbsolute));
                        break;
                    default:
                        this.ContentFrame.Navigate(new Uri("/History", UriKind.Relative));
                        break;
                }
            }
            this.IsEnabled = true;
        }
        #endregion
    }
}